<template>
  <div class="stock-inquiry">
    <!-- 时间筛选区域 -->
    <div class="time-filter-section">
      <div class="time-filter-buttons">
        <button
          v-for="filter in timeFilters"
          :key="filter.key"
          :class="[
            'time-filter-btn',
            { active: activeTimeFilter === filter.key },
          ]"
          @click="handleTimeFilterChange(filter.key)"
        >
          {{ filter.label }}
        </button>
      </div>

      <!-- 自定义时间选择器 -->
      <div v-if="showCustomDatePicker" class="custom-date-picker">
        <el-date-picker
          v-model="customDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleCustomDateChange"
          style="width: 300px"
        />
      </div>
    </div>

    <!-- 搜索和过滤区域 -->
    <div class="search-filter-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="货品">
          <el-input
            v-model="searchForm.Product_Name"
            placeholder="请输入货品名称/编号"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品类型：">
          <el-tree-select
            v-model="searchForm.Category_Id"
            :data="categoryTreeList"
            placeholder="请选择"
            clearable
            check-strictly
            :props="{
              children: 'children',
              label: 'category_Name',
              value: 'id',
            }"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="单位：">
          <el-select
            v-model="searchForm.Unit_Id"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in UnitList"
              :label="item.unit_Name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称：">
          <el-select
            v-model="searchForm.Warehouse_Id"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in warehouseList"
              :label="item.warehouse_Name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货品条码">
          <el-input
            v-model="searchForm.Internal_Code"
            placeholder="请输入货品条码"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.Status">显示停用商品</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="searchData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistics-cards">
      <div class="stat-card blue">
        <div class="stat-number">{{ totalStats.currentStockQuantity }}</div>
        <div class="stat-label">当前库存数量</div>
      </div>
      <div class="stat-card blue">
        <div class="stat-number">{{ totalStats.currentStockAmount }}</div>
        <div class="stat-label">当前库存金额</div>
      </div>
      <div class="stat-card green">
        <div class="stat-number">{{ totalStats.inboundQuantity }}</div>
        <div class="stat-label">入库数量</div>
      </div>
    </div>
    <div class="statistics-cards">
      <div class="stat-card orange">
        <div class="stat-number">{{ totalStats.outboundQuantity }}</div>
        <div class="stat-label">出库数量</div>
      </div>
      <div class="stat-card green">
        <div class="stat-number">{{ totalStats.pendingInbound }}</div>
        <div class="stat-label">待入库</div>
      </div>
      <div class="stat-card orange">
        <div class="stat-number">{{ totalStats.pendingOutbound }}</div>
        <div class="stat-label">待出库</div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button @click="refreshData">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="product_Number" label="货品编号" width="120" />
        <el-table-column prop="product_Name" label="货品名称" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category_Name" label="货品类型" width="120" />
        <el-table-column prop="specifications" label="规格型号" width="100" />
        <el-table-column prop="unit_Name" label="单位" width="80" />
        <el-table-column prop="internal_Code" label="条码" width="120" />
        <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
        <el-table-column prop="storage_Name" label="库位名称" width="120" />
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column prop="waitInTo" label="待入库" width="120" />
        <el-table-column prop="waitOutTo" label="待出库" width="120" />
        <el-table-column
          prop="warehouse_InOrOutCount"
          label="可用库存"
          width="120"
        />
        <el-table-column
          prop="availableAmount"
          label="可用库存金额"
          width="120"
        />
        <el-table-column prop="intTo" label="期初" width="120" />
        <el-table-column prop="end" label="期末" width="120" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-link type="primary" @click="viewFlow(scope.row)"
              >出入库流水</el-link
            >
            <el-link
              type="primary"
              @click="viewDistribution(scope.row)"
              style="margin-left: 10px"
              >库存分布</el-link
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[15, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 库存分布全屏弹窗 -->
  <el-dialog
    v-model="distributionDialogVisible"
    title="库存分布详情"
    :fullscreen="true"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="distribution-dialog"
  >
    <div class="distribution-content">
      <!-- 产品信息头部 -->
      <div class="product-header" v-if="currentProduct">
        <div class="product-info">
          <h2>
            {{
              currentProduct.product_Name ||
              currentProduct.productName ||
              "未知产品"
            }}
          </h2>
          <div class="product-details">
            <span class="detail-item"
              >货品编号：{{
                currentProduct.product_Number ||
                currentProduct.productNumber ||
                "-"
              }}</span
            >
            <span class="detail-item"
              >货品类型：{{ currentProduct.category_Name || "-" }}</span
            >
            <span class="detail-item"
              >规格型号：{{ currentProduct.specifications || "-" }}</span
            >
            <span class="detail-item"
              >单位：{{ currentProduct.unit_Name || "-" }}</span
            >
          </div>
        </div>
      </div>

      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <div class="stat-card blue">
          <div class="stat-number">
            {{ distributionStats.currentStock || 0 }}
          </div>
          <div class="stat-label">当前库存</div>
        </div>
        <div class="stat-card blue">
          <div class="stat-number">
            {{ distributionStats.availableStock || 0 }}
          </div>
          <div class="stat-label">可用库存</div>
        </div>
        <div class="stat-card orange">
          <div class="stat-number">
            {{ distributionStats.pendingOutbound || 0 }}
          </div>
          <div class="stat-label">待出库</div>
        </div>
        <div class="stat-card orange">
          <div class="stat-number">
            {{ distributionStats.pendingInbound || 0 }}
          </div>
          <div class="stat-label">待入库</div>
        </div>
      </div>

      <!-- 库存分布表格 -->
      <div class="table-section">
        <el-table
          :data="distributionData"
          style="width: 100%"
          v-loading="distributionLoading"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="150">
          </el-table-column>
          <el-table-column prop="storage_Name" label="仓位名称" width="150">
          </el-table-column>
          <el-table-column prop="currentInventory" label="当前库存" width="120">
          </el-table-column>
          <el-table-column
            prop="warehouse_InOrOutCount"
            label="可用库存"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="waitInTo" label="待入库" width="120">
          </el-table-column>
          <el-table-column prop="waitOutTo" label="待出库" width="120">
          </el-table-column>
        </el-table>
      </div>

      <!-- 右下角关闭按钮 -->
      <div class="close-button-container">
        <el-button
          type="primary"
          size="large"
          circle
          @click="distributionDialogVisible = false"
          class="close-button"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
  </el-dialog>

  <!-- 出入库流水全屏弹窗 -->
  <el-dialog
    v-model="flowDialogVisible"
    title="出入库流水"
    :fullscreen="true"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="flow-dialog"
  >
    <div class="flow-content">
      <!-- 产品信息头部 -->
      <div class="product-header" v-if="currentProduct">
        <div class="product-info">
          <h2>
            {{ currentProduct.product_Name }}
            {{
              currentProduct.product_Number ||
              currentProduct.productNumber ||
              ""
            }}
          </h2>
          <div class="product-details">
            <span class="detail-item"
              >货品类型：{{ currentProduct.category_Name }}</span
            >
            <span class="detail-item"
              >规格型号：{{ currentProduct.specifications }}</span
            >
            <span class="detail-item"
              >单位：{{ currentProduct.unit_Name }}</span
            >
          </div>
        </div>
      </div>

      <!-- 搜索和过滤区域 -->
      <div class="search-filter-section">
        <el-form :model="flowSearchForm" inline>
          <el-form-item label="出入库单号">
            <el-input
              v-model="flowSearchForm.Warehouse_Code"
              placeholder="请输入出库单号/入库单号"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-select
              v-model="flowSearchForm.Warehouse_Name"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="warehouse in warehouseOptions"
                :key="warehouse.value"
                :label="warehouse.label"
                :value="warehouse.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="业务类型">
            <el-select
              v-model="flowSearchForm.WarehouseType"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="入库" :value="1" />
              <el-option label="出库" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="出入库类型">
            <el-select
              v-model="flowSearchForm.Warehousing_Type"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="采购收货入库" value="采购收货入库" />
              <el-option label="销售出库" value="销售出库" />
              <el-option label="销售退货入库" value="销售退货入库" />
              <el-option label="生产产品入库" value="生产产品入库" />
              <el-option label="领用退还入库" value="领用退还入库" />
              <el-option label="生产领用出库" value="生产领用出库" />
              <el-option label="领用退还出库" value="领用退还出库" />
              <el-option label="调拨入库" value="调拨入库" />
              <el-option label="调拨出库" value="调拨出库" />
              <el-option label="移动入库" value="移动入库" />
              <el-option label="移动出库" value="移动出库" />
            </el-select>
          </el-form-item>
          <el-form-item label="出入库日期">
            <el-date-picker
              v-model="flowSearchForm.startDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="制单日期">
            <el-date-picker
              v-model="flowSearchForm.CreateTime"
              type="date"
              placeholder="请选择制单日期"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="resetFlowSearch">重置</el-button>
            <el-button type="primary" @click="searchFlowData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计卡片 -->
      <div class="statistics-cards">
        <div class="stat-card blue">
          <div class="stat-number">{{ flowStats.inboundQuantity }}</div>
          <div class="stat-label">入库数量</div>
        </div>
        <div class="stat-card blue">
          <div class="stat-number">{{ flowStats.inboundAmount }}</div>
          <div class="stat-label">入库金额</div>
        </div>
        <div class="stat-card orange">
          <div class="stat-number">{{ flowStats.outboundQuantity }}</div>
          <div class="stat-label">出库数量</div>
        </div>
        <div class="stat-card orange">
          <div class="stat-number">{{ flowStats.outboundAmount }}</div>
          <div class="stat-label">出库金额</div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleExportFlow">导出</el-button>
        <el-button @click="refreshFlowData">刷新</el-button>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table
          :data="flowData"
          style="width: 100%"
          v-loading="flowLoading"
          @selection-change="handleFlowSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column
            prop="warehouse_Code"
            label="出入库单号"
            width="150"
          />
          <el-table-column prop="reviewTime" label="出入库日期" width="120">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.reviewTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseType" label="业务类型" width="100">
            <template #default="scope">
              <span v-if="scope.row.warehouseType === 1">入库</span>
              <span v-else-if="scope.row.warehouseType === 2">出库</span>
              <span v-else>{{ scope.row.warehouseType }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehousing_Type"
            label="出入库类型"
            width="120"
          />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
          <el-table-column
            prop="warehouse_InOrOutCount"
            label="入库数量"
            width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.warehouseType === 1">{{
                scope.row.warehouse_InOrOutCount || 0
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouse_InOrOutCount"
            label="出库数量"
            width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.warehouseType === 2">{{
                scope.row.warehouse_InOrOutCount || 0
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="入库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType === 1">{{
                scope.row.total_Price || 0
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="出库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType === 2">{{
                scope.row.total_Price || 0
              }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="reviewer" label="经办人" width="100" />
          <el-table-column prop="creatorName" label="制单人" width="100">
          </el-table-column>
          <el-table-column prop="createTime" label="制单时间" width="120">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="flowCurrentPage"
            v-model:page-size="flowPageSize"
            :page-sizes="[15, 30, 50, 100]"
            :total="flowTotal"
            layout="total, sizes, prev, pager, next"
            @size-change="handleFlowSizeChange"
            @current-change="handleFlowCurrentChange"
          />
        </div>
      </div>

      <!-- 右下角关闭按钮 -->
      <div class="close-button-container">
        <el-button
          type="primary"
          size="large"
          circle
          @click="flowDialogVisible = false"
          class="close-button"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { StorageRed } from "@/http/axiosHelper";
import { ElMessage } from "element-plus";
import { Close } from "@element-plus/icons-vue";
// import { StorageRed } from "@/http/axiosHelper";
// 响应式数据
const activeTimeFilter = ref("today");
const showCustomDatePicker = ref(false);
const customDateRange = ref([]);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const selectedRows = ref([]);
const loading = ref(false);

// 时间筛选选项
const timeFilters = ref([
  { key: "today", label: "今日" },
  { key: "yesterday", label: "昨日" },
  { key: "thisWeek", label: "本周" },
  { key: "lastWeek", label: "上周" },
  { key: "thisMonth", label: "本月" },
  { key: "lastMonth", label: "上月" },
  { key: "lastHalfYear", label: "最近半年" },
  { key: "lastYear", label: "最近一年" },
  { key: "custom", label: "自定义时间" },
]);

// 生命周期
onMounted(async () => {
  fetchData();
  getWarehouseList();
  getUnitList();
  getCategoryTreeList();
});

// 搜索表单
const searchForm = reactive({
  Product_Name: "",
  Category_Id: "",
  Unit_Id: "",
  Warehouse_Id: "",
  Internal_Code: "",
  Status: "",
  startDate: "",
  endDate: "",
});

// 表格数据
const tableData = ref([]);

// 统计数据
const totalStats = ref({
  currentStockQuantity: 0,
  currentStockAmount: 0,
  inboundQuantity: 0,
  outboundQuantity: 0,
  pendingInbound: 0,
  pendingOutbound: 0,
});

// 仓库列表
const warehouseList = ref([]);
// 获取仓库列表
const getWarehouseList = () => {
  StorageRed({
    url: "/api/Warehouse_InOrOut/GetWarehouseModel",
    method: "get",
  }).then((res) => {
    warehouseList.value = res.data.data;
  });
};

// 单位列表
const UnitList = ref([]);
// 获取单位列表
const getUnitList = () => {
  StorageRed({
    url: "/api/WorkOrder/GetUnitDropdown",
    method: "get",
  }).then((res) => {
    UnitList.value = res.data.data;
  });
};

// 产品类型树形列表
const categoryTreeList = ref([]);
// 获取产品类型树形结构
const getCategoryTreeList = () => {
  StorageRed({
    url: "/api/WorkOrder/GetProductCategoryTree",
    method: "get",
  }).then((res) => {
    categoryTreeList.value = res.data.data;
  });
};

// 选项数据
const warehouseOptions = ref([]);

// 计算统计数据
const calculateStats = (data) => {
  const stats = {
    currentStockQuantity: 0,
    currentStockAmount: 0,
    inboundQuantity: 0,
    outboundQuantity: 0,
    pendingInbound: 0,
    pendingOutbound: 0,
  };

  data.forEach((item) => {
    // 当前库存数量
    stats.currentStockQuantity += Number(item.currentInventory || 0);

    // 当前库存金额
    stats.currentStockAmount += Number(item.availableAmount || 0);

    // 待入库数量
    stats.pendingInbound += Number(item.waitInTo || 0);

    // 待出库数量
    stats.pendingOutbound += Number(item.waitOutTo || 0);

    // 入库数量（这里需要根据实际业务逻辑调整）
    // 假设从期初到期末的差额作为入库数量
    const inboundDiff = Number(item.end || 0) - Number(item.intTo || 0);
    if (inboundDiff > 0) {
      stats.inboundQuantity += inboundDiff;
    }

    // 出库数量（这里需要根据实际业务逻辑调整）
    // 假设可用库存与当前库存的差额作为出库数量
    const outboundDiff =
      Number(item.currentInventory || 0) -
      Number(item.warehouse_InOrOutCount || 0);
    if (outboundDiff > 0) {
      stats.outboundQuantity += outboundDiff;
    }
  });

  // 格式化金额，保留两位小数
  stats.currentStockAmount = Number(stats.currentStockAmount.toFixed(2));

  return stats;
};

// 获取数据方法
const fetchData = async () => {
  loading.value = true;

  try {
    const params = {
      Product_Name: searchForm.Product_Name || "",
      Category_Id: searchForm.Category_Id || "",
      Unit_Id: searchForm.Unit_Id || "",
      Warehouse_Id: searchForm.Warehouse_Id || "",
      Internal_Code: searchForm.Internal_Code || "",
      Status: searchForm.Status || "",
      startDate: searchForm.startDate || "",
      endDate: searchForm.endDate || "",
      PageIndex: currentPage.value,
      PageSize: pageSize.value,
    };

    console.log("查询参数:", params);

    const response = await StorageRed.get("/api/WorkOrder/GetLedgar", {
      params,
    });

    console.log("查询结果:", response);

    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map((item) => ({
        product_Number:
          item.product_Number ||
          item.productNumber ||
          item.Product_Number ||
          "",
        product_Name:
          item.product_Name || item.productName || item.Product_Name || "",
        status: item.status || item.Status || "正常",
        category_Name:
          item.category_Name || item.categoryName || item.Category_Name || "",
        specifications: item.specifications || item.Specifications || "",
        unit_Name: item.unit_Name || item.unitName || item.Unit_Name || "",
        internal_Code:
          item.internal_Code || item.internalCode || item.Internal_Code || "",
        warehouse_Name:
          item.warehouse_Name ||
          item.warehouseName ||
          item.Warehouse_Name ||
          "",
        storage_Name:
          item.storage_Name || item.storageName || item.Storage_Name || "",
        currentInventory: Number(
          item.currentInventory ||
            item.currentStock ||
            item.CurrentInventory ||
            0
        ),
        waitInTo: Number(
          item.waitInTo || item.pendingInbound || item.WaitInTo || 0
        ),
        waitOutTo: Number(
          item.waitOutTo || item.pendingOutbound || item.WaitOutTo || 0
        ),
        warehouse_InOrOutCount: Number(
          item.warehouse_InOrOutCount ||
            item.availableStock ||
            item.Warehouse_InOrOutCount ||
            0
        ),
        availableAmount: Number(
          item.availableAmount || item.AvailableAmount || 0
        ),
        intTo: Number(item.intTo || item.IntTo || 0),
        end: Number(item.end || item.End || 0),
        // 保留原始数据用于其他操作
        ...item,
      }));

      tableData.value = processedData;
      total.value = response.data.totalCount || 0;

      // 计算统计数据
      totalStats.value = calculateStats(processedData);

      console.log("设置表格数据:", tableData.value);
      console.log("设置总数:", total.value);
      console.log("设置统计数据:", totalStats.value);
    } else {
      console.log("响应数据为空或格式不正确");
      tableData.value = [];
      total.value = 0;
      totalStats.value = {
        currentStockQuantity: 0,
        currentStockAmount: 0,
        inboundQuantity: 0,
        outboundQuantity: 0,
        pendingInbound: 0,
        pendingOutbound: 0,
      };
    }
  } catch (error) {
    console.error("查询失败:", error);
    console.error("错误详情:", error.response?.data);
    console.error("错误状态:", error.response?.status);
    tableData.value = [];
    total.value = 0;
    totalStats.value = {
      currentStockQuantity: 0,
      currentStockAmount: 0,
      inboundQuantity: 0,
      outboundQuantity: 0,
      pendingInbound: 0,
      pendingOutbound: 0,
    };
    ElMessage.error("查询失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间，去掉T
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return "";
  return dateTimeStr.replace("T", " ");
};

// 获取时间范围的辅助函数
const getDateRange = (filterKey) => {
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  switch (filterKey) {
    case "today":
      return {
        startDate: today,
        endDate: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1),
      };
    case "yesterday":
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
      return {
        startDate: yesterday,
        endDate: new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1),
      };
    case "thisWeek":
      const thisWeekStart = new Date(today);
      thisWeekStart.setDate(today.getDate() - today.getDay());
      return {
        startDate: thisWeekStart,
        endDate: new Date(
          thisWeekStart.getTime() + 7 * 24 * 60 * 60 * 1000 - 1
        ),
      };
    case "lastWeek":
      const lastWeekStart = new Date(today);
      lastWeekStart.setDate(today.getDate() - today.getDay() - 7);
      return {
        startDate: lastWeekStart,
        endDate: new Date(
          lastWeekStart.getTime() + 7 * 24 * 60 * 60 * 1000 - 1
        ),
      };
    case "thisMonth":
      const thisMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const thisMonthEnd = new Date(
        now.getFullYear(),
        now.getMonth() + 1,
        0,
        23,
        59,
        59
      );
      return {
        startDate: thisMonthStart,
        endDate: thisMonthEnd,
      };
    case "lastMonth":
      const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      const lastMonthEnd = new Date(
        now.getFullYear(),
        now.getMonth(),
        0,
        23,
        59,
        59
      );
      return {
        startDate: lastMonthStart,
        endDate: lastMonthEnd,
      };
    case "lastHalfYear":
      const halfYearAgo = new Date(
        now.getFullYear(),
        now.getMonth() - 6,
        now.getDate()
      );
      return {
        startDate: halfYearAgo,
        endDate: now,
      };
    case "lastYear":
      const yearAgo = new Date(
        now.getFullYear() - 1,
        now.getMonth(),
        now.getDate()
      );
      return {
        startDate: yearAgo,
        endDate: now,
      };
    default:
      return {
        startDate: null,
        endDate: null,
      };
  }
};

// 格式化日期为字符串
const formatDateToString = (date) => {
  if (!date) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 时间筛选方法
const handleTimeFilterChange = (filterKey) => {
  console.log("时间筛选变化:", filterKey);
  activeTimeFilter.value = filterKey;

  if (filterKey === "custom") {
    showCustomDatePicker.value = true;
    return;
  } else {
    showCustomDatePicker.value = false;
  }

  // 获取时间范围并更新搜索条件
  const dateRange = getDateRange(filterKey);
  searchForm.startDate = formatDateToString(dateRange.startDate);
  searchForm.endDate = formatDateToString(dateRange.endDate);

  console.log("设置时间范围:", searchForm.startDate, "至", searchForm.endDate);

  // 重新查询数据
  currentPage.value = 1;
  fetchData();
};

// 自定义时间选择变化
const handleCustomDateChange = (dateRange) => {
  console.log("自定义时间范围变化:", dateRange);
  if (dateRange && dateRange.length === 2) {
    searchForm.startDate = dateRange[0];
    searchForm.endDate = dateRange[1];

    // 重新查询数据
    currentPage.value = 1;
    fetchData();
  }
};

const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  // 重置时间筛选
  activeTimeFilter.value = "today";
  showCustomDatePicker.value = false;
  customDateRange.value = [];

  currentPage.value = 1;
  fetchData();
};

const searchData = () => {
  console.log("搜索条件:", searchForm);
  currentPage.value = 1;
  fetchData();
};

// 导出函数
async function handleExport() {
  try {
    // 显示加载提示
    ElMessage.info("正在导出数据，请稍候...");

    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await StorageRed({
      url: "/api/WorkOrder/GetledgarExport", // 后端接口地址
      method: "GET",
      params: {
        // 传递搜索条件
        Product_Name: searchForm.Product_Name || "",
        Category_Id: searchForm.Category_Id || "",
        Unit_Id: searchForm.Unit_Id || "",
        Warehouse_Id: searchForm.Warehouse_Id || "",
        Internal_Code: searchForm.Internal_Code || "",
        Status: searchForm.Status || "",
        startDate: searchForm.startDate || "",
        endDate: searchForm.endDate || "",
        PageIndex: currentPage.value,
        PageSize: pageSize.value,
      },
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    // 5. 显示成功提示
    ElMessage.success("导出成功！");
  } catch (error) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    ElMessage.error("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "库存查询.xlsx"; // 默认文件名

  // 尝试多种文件名提取方式
  let fileName = "库存查询.xlsx";

  // 方式1：标准格式 filename="xxx"
  const standardMatch = contentDisposition.match(/filename="([^"]+)"/);
  if (standardMatch) {
    fileName = standardMatch[1];
  }
  // 方式2：UTF-8编码格式 filename*=UTF-8''xxx
  else {
    const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/);
    if (utf8Match) {
      fileName = decodeURIComponent(utf8Match[1]);
    }
    // 方式3：简单格式 filename=xxx
    else {
      const simpleMatch = contentDisposition.match(/filename=([^;]+)/);
      if (simpleMatch) {
        fileName = decodeURIComponent(simpleMatch[1]);
      }
    }
  }

  // 确保文件名有正确的扩展名
  if (
    !fileName.toLowerCase().endsWith(".xlsx") &&
    !fileName.toLowerCase().endsWith(".xls")
  ) {
    fileName += ".xlsx";
  }

  return fileName;
}

const refreshData = () => {
  console.log("刷新数据");
  fetchData();
};

const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
  console.log("选中的行:", selection);
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  console.log("每页显示数量变化:", size);
  fetchData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  console.log("当前页变化:", page);
  fetchData();
};

const viewFlow = async (row) => {
  console.log("查看出入库流水:", row);
  currentProduct.value = row;
  flowDialogVisible.value = true;

  // 获取出入库流水数据
  await fetchFlowData();
};

// 库存分布弹窗相关数据
const distributionDialogVisible = ref(false);
const currentProduct = ref(null);
const distributionData = ref([]);
const distributionLoading = ref(false);

// 库存分布统计数据
const distributionStats = ref({
  currentStock: 0,
  availableStock: 0,
  pendingOutbound: 0,
  pendingInbound: 0,
});

const viewDistribution = async (row) => {
  console.log("查看库存分布:", row);
  console.log("产品详细信息:", {
    product_Id: row.product_Id,
    productId: row.productId,
    product_Name: row.product_Name,
    productName: row.productName,
    product_Number: row.product_Number,
    productNumber: row.productNumber,
  });

  currentProduct.value = row;
  distributionDialogVisible.value = true;

  // 获取库存分布数据
  await fetchDistributionData(row);
};

// 获取库存分布数据
const fetchDistributionData = async (product) => {
  distributionLoading.value = true;

  try {
    const params = {
      Product_Id: product.product_Id || product.productId || "",
      Product_Name: product.product_Name || product.productName || "",
      Product_Number: product.product_Number || product.productNumber || "",
      PageIndex: 1,
      PageSize: 100,
    };

    console.log("库存分布查询参数:", params);

    const response = await StorageRed.get("/api/WorkOrder/GetDistribution", {
      params,
    });

    console.log("库存分布查询结果:", response);

    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map((item) => ({
        warehouse_Name:
          item.warehouse_Name ||
          item.warehouseName ||
          item.Warehouse_Name ||
          "",
        storage_Name:
          item.storage_Name || item.storageName || item.Storage_Name || "",
        currentInventory: Number(
          item.currentInventory ||
            item.currentStock ||
            item.CurrentInventory ||
            0
        ),
        warehouse_InOrOutCount: Number(
          item.warehouse_InOrOutCount ||
            item.availableStock ||
            item.Warehouse_InOrOutCount ||
            0
        ),
        waitInTo: Number(
          item.waitInTo || item.pendingInbound || item.WaitInTo || 0
        ),
        waitOutTo: Number(
          item.waitOutTo || item.pendingOutbound || item.WaitOutTo || 0
        ),
      }));

      distributionData.value = processedData;

      // 计算统计数据
      distributionStats.value = {
        currentStock: processedData.reduce(
          (sum, item) => sum + item.currentInventory,
          0
        ),
        availableStock: processedData.reduce(
          (sum, item) => sum + item.warehouse_InOrOutCount,
          0
        ),
        pendingOutbound: processedData.reduce(
          (sum, item) => sum + item.waitOutTo,
          0
        ),
        pendingInbound: processedData.reduce(
          (sum, item) => sum + item.waitInTo,
          0
        ),
      };

      console.log("设置库存分布数据:", distributionData.value);
      console.log("设置统计数据:", distributionStats.value);
    } else {
      console.log("库存分布响应数据为空或格式不正确");
      distributionData.value = [];
      distributionStats.value = {
        currentStock: 0,
        availableStock: 0,
        pendingOutbound: 0,
        pendingInbound: 0,
      };
    }
  } catch (error) {
    console.error("获取库存分布数据失败:", error);
    console.error("错误详情:", error.response?.data);
    console.error("错误状态:", error.response?.status);

    let errorMessage = "获取库存分布数据失败，请稍后重试";
    if (error.response?.status === 404) {
      errorMessage = "库存分布接口不存在，请联系管理员";
    } else if (error.response?.status === 401) {
      errorMessage = "登录已过期，请重新登录";
    } else if (error.response?.status === 500) {
      errorMessage = "服务器内部错误，请联系管理员";
    } else if (!error.response) {
      errorMessage = "网络连接失败，请检查网络连接";
    }

    distributionData.value = [];
    distributionStats.value = {
      currentStock: 0,
      availableStock: 0,
      pendingOutbound: 0,
      pendingInbound: 0,
    };
    ElMessage.error(errorMessage);
  } finally {
    distributionLoading.value = false;
  }
};

// 出入库流水弹窗相关数据
const flowDialogVisible = ref(false);
const flowSearchForm = reactive({
  Warehouse_Code: "",
  Warehousing_Type: "",
  Warehouse_Name: "",
  WarehouseType: "",
  startDate: null,
  EndDate: null,
  CreateTime: null,
});
const flowData = ref([]);
const flowLoading = ref(false);
const flowCurrentPage = ref(1);
const flowPageSize = ref(15);
const flowTotal = ref(0);
const flowSelectedRows = ref([]);

// 出入库流水统计数据
const flowStats = ref({
  inboundQuantity: 0,
  inboundAmount: 0,
  outboundQuantity: 0,
  outboundAmount: 0,
});

const searchFlowData = () => {
  console.log("出入库流水搜索条件:", flowSearchForm);
  flowCurrentPage.value = 1;
  fetchFlowData();
};

const resetFlowSearch = () => {
  Object.keys(flowSearchForm).forEach((key) => {
    if (key === "startDate" || key === "EndDate" || key === "CreateTime") {
      flowSearchForm[key] = null;
    } else {
      flowSearchForm[key] = "";
    }
  });
  flowCurrentPage.value = 1;
  console.log("重置后的出入库流水搜索表单:", flowSearchForm);
  fetchFlowData();
};

const fetchFlowData = async () => {
  flowLoading.value = true;

  try {
    // 格式化日期函数，确保显示准确的日期
    const formatDate = (date) => {
      if (!date) return "";
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    };

    const params = {
      Product_Id:
        currentProduct.value?.product_Id ||
        currentProduct.value?.productId ||
        "",
      Product_Name:
        currentProduct.value?.product_Name ||
        currentProduct.value?.productName ||
        "",
      Product_Number:
        currentProduct.value?.product_Number ||
        currentProduct.value?.productNumber ||
        "",
      Warehouse_Code: flowSearchForm.Warehouse_Code || "",
      Warehouse_Name: flowSearchForm.Warehouse_Name || "",
      Warehousing_Type: flowSearchForm.Warehousing_Type || "",
      WarehouseType: flowSearchForm.WarehouseType || "",
      startDate:
        flowSearchForm.startDate && flowSearchForm.startDate[0]
          ? formatDate(flowSearchForm.startDate[0])
          : "",
      EndDate:
        flowSearchForm.startDate && flowSearchForm.startDate[1]
          ? formatDate(flowSearchForm.startDate[1])
          : "",
      CreateTime: flowSearchForm.CreateTime
        ? formatDate(flowSearchForm.CreateTime)
        : "",
      PageIndex: flowCurrentPage.value,
      PageSize: flowPageSize.value,
    };

    console.log("出入库流水查询参数:", params);

    const response = await StorageRed.get(
      "/api/WorkOrder/StorageGetWarehouse_InOrOut",
      { params }
    );

    console.log("出入库流水查询结果:", response);

    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map((item) => ({
        warehouse_Code:
          item.warehouse_Code ||
          item.warehouseCode ||
          item.Warehouse_Code ||
          "",
        reviewTime: item.reviewTime || item.ReviewTime || "",
        warehouseType: Number(item.warehouseType || item.WarehouseType || 0),
        warehousing_Type:
          item.warehousing_Type ||
          item.warehousingType ||
          item.Warehousing_Type ||
          "",
        warehouse_Name:
          item.warehouse_Name ||
          item.warehouseName ||
          item.Warehouse_Name ||
          "",
        warehouse_InOrOutCount: Number(
          item.warehouse_InOrOutCount || item.Warehouse_InOrOutCount || 0
        ),
        total_Price: Number(
          item.total_Price || item.totalPrice || item.Total_Price || 0
        ),
        reviewer: item.reviewer || item.Reviewer || "",
        createUse: item.createUse || item.createUser || item.CreateUse || "",
        createTime: item.createTime || item.createTime || item.CreateTime || "",
        // 保留原始数据
        ...item,
      }));

      flowData.value = processedData;
      flowTotal.value = response.data.totalCount || 0;

      // 根据业务类型计算统计数据
      let inboundQuantity = 0;
      let inboundAmount = 0;
      let outboundQuantity = 0;
      let outboundAmount = 0;

      processedData.forEach((item) => {
        if (item.warehouseType === 1) {
          inboundQuantity += Number(item.warehouse_InOrOutCount) || 0;
          inboundAmount += Number(item.total_Price) || 0;
        } else if (item.warehouseType === 2) {
          outboundQuantity += Number(item.warehouse_InOrOutCount) || 0;
          outboundAmount += Number(item.total_Price) || 0;
        }
      });

      flowStats.value = {
        inboundQuantity,
        inboundAmount,
        outboundQuantity,
        outboundAmount,
      };

      console.log("设置出入库流水数据:", flowData.value);
      console.log("设置出入库流水总数:", flowTotal.value);
      console.log("设置统计数据:", flowStats.value);
    } else {
      console.log("出入库流水响应数据为空或格式不正确");
      flowData.value = [];
      flowTotal.value = 0;
      flowStats.value = {
        inboundQuantity: 0,
        inboundAmount: 0,
        outboundQuantity: 0,
        outboundAmount: 0,
      };
    }
  } catch (error) {
    console.error("获取出入库流水数据失败:", error);
    console.error("错误详情:", error.response?.data);
    console.error("错误状态:", error.response?.status);
    console.error("错误信息:", error.message);

    let errorMessage = "获取出入库流水数据失败，请稍后重试";
    if (error.response?.status === 404) {
      errorMessage = "出入库流水接口不存在，请联系管理员";
    } else if (error.response?.status === 401) {
      errorMessage = "登录已过期，请重新登录";
    } else if (error.response?.status === 500) {
      errorMessage = "服务器内部错误，请联系管理员";
    } else if (!error.response) {
      errorMessage = "网络连接失败，请检查网络连接";
    }

    flowData.value = [];
    flowTotal.value = 0;
    flowStats.value = {
      inboundQuantity: 0,
      inboundAmount: 0,
      outboundQuantity: 0,
      outboundAmount: 0,
    };
    ElMessage.error(errorMessage);
  } finally {
    flowLoading.value = false;
  }
};

const handleFlowSelectionChange = (selection) => {
  flowSelectedRows.value = selection;
  console.log("选中的出入库流水行:", selection);
};

const handleFlowSizeChange = (size) => {
  flowPageSize.value = size;
  flowCurrentPage.value = 1;
  console.log("出入库流水每页显示数量变化:", size);
  fetchFlowData();
};

const handleFlowCurrentChange = (page) => {
  flowCurrentPage.value = page;
  console.log("出入库流水当前页变化:", page);
  fetchFlowData();
};

async function handleExportFlow() {
  try {
    // 显示加载提示
    ElMessage.info("正在导出出入库流水数据，请稍候...");

    // 格式化日期函数，确保显示准确的日期
    const formatDate = (date) => {
      if (!date) return "";
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    };

    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await StorageRed({
      url: "/api/WorkOrder/StorageGetWarehouse_InOrOutExport", // 后端接口地址
      method: "GET",
      params: {
        // 传递产品信息
        Product_Id:
          currentProduct.value?.product_Id ||
          currentProduct.value?.productId ||
          "",
        Product_Name:
          currentProduct.value?.product_Name ||
          currentProduct.value?.productName ||
          "",
        Product_Number:
          currentProduct.value?.product_Number ||
          currentProduct.value?.productNumber ||
          "",
        // 传递查询条件
        Warehouse_Code: flowSearchForm.Warehouse_Code || "",
        Warehouse_Name: flowSearchForm.Warehouse_Name || "",
        Warehousing_Type: flowSearchForm.Warehousing_Type || "",
        WarehouseType: flowSearchForm.WarehouseType || "",
        startDate:
          flowSearchForm.startDate && flowSearchForm.startDate[0]
            ? formatDate(flowSearchForm.startDate[0])
            : "",
        EndDate:
          flowSearchForm.startDate && flowSearchForm.startDate[1]
            ? formatDate(flowSearchForm.startDate[1])
            : "",
        CreateTime: flowSearchForm.CreateTime
          ? formatDate(flowSearchForm.CreateTime)
          : "",
        // 分页参数
        PageIndex: flowCurrentPage.value,
        PageSize: flowPageSize.value,
      },
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    // 5. 显示成功提示
    ElMessage.success("出入库流水数据导出成功！");
  } catch (error) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    ElMessage.error("导出失败，请稍后重试");
  }
}

const refreshFlowData = () => {
  console.log("刷新出入库流水数据");
  fetchFlowData();
};
</script>

<style scoped>
.stock-inquiry {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.time-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

/* 时间筛选区域样式 */
.time-filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

.time-filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.time-filter-btn {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: white;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  min-width: 80px;
  text-align: center;
}

.time-filter-btn:hover {
  border-color: #67c23a;
  color: #67c23a;
}

.time-filter-btn.active {
  background: #67c23a;
  border-color: #67c23a;
  color: white;
  font-weight: 500;
}

.custom-date-picker {
  margin-top: 10px;
}

.search-filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

.time-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 25px;
  margin-bottom: 30px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.statistics-cards:last-of-type {
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 40px 30px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  min-height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-card.blue .stat-number {
  color: #409eff;
  font-size: 36px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-card.green .stat-number {
  color: #67c23a;
  font-size: 36px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
  font-size: 36px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-label {
  color: #666;
  font-size: 16px;
  margin-top: 12px;
  font-weight: 500;
}

.action-buttons {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

.pagination-section {
  padding: 20px;
  text-align: right;
  background: white;
  border-top: 1px solid #ebeef5;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
}

:deep(.el-tabs__item.is-active) {
  color: #67c23a;
}

:deep(.el-tabs__active-bar) {
  background-color: #67c23a;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
}

:deep(.el-link) {
  font-size: 14px;
}

/* 库存分布弹窗样式 */
.distribution-dialog {
  :deep(.el-dialog) {
    margin: 0;
    border-radius: 0;
  }

  :deep(.el-dialog__header) {
    background: #f5f5f5;
    padding: 15px 20px;
    border-bottom: 1px solid #e4e7ed;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 60px);
    overflow-y: auto;
  }
}

.distribution-content {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.product-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.product-info h2 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 24px;
}

/* 出入库流水弹窗样式 */
.flow-dialog {
  :deep(.el-dialog) {
    margin: 0;
    border-radius: 0;
  }

  :deep(.el-dialog__header) {
    background: #f5f5f5;
    padding: 15px 20px;
    border-bottom: 1px solid #e4e7ed;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 60px);
    overflow-y: auto;
  }
}

.flow-content {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.product-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.product-info h2 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 24px;
}

.product-details {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.detail-item {
  color: #606266;
  font-size: 14px;
}

/* 弹窗中的统计卡片样式 */
.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 25px;
  margin-bottom: 25px;
}

.stat-card {
  background: white;
  padding: 30px 25px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.stat-card.blue .stat-number {
  color: #409eff;
  font-size: 32px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-card.green .stat-number {
  color: #67c23a;
  font-size: 32px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
  font-size: 32px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-label {
  color: #666;
  font-size: 15px;
  margin-top: 10px;
  font-weight: 500;
}

/* 弹窗中的操作按钮和表格样式 */
.action-buttons {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  padding: 20px;
  text-align: right;
  background: white;
  border-top: 1px solid #ebeef5;
}

/* 关闭按钮样式 */
.close-button-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 2001;
}

.close-button {
  width: 60px;
  height: 60px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.close-button:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.close-button .el-icon {
  font-size: 24px;
}

/* 查询区域下拉框专用样式 */
.search-filter-section {
  :deep(.el-form-item) {
    margin-bottom: 18px;
    margin-right: 20px;
  }

  :deep(.el-form-item__label) {
    color: #303133;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.5;
    white-space: nowrap;
  }

  /* 货品类型树形选择器 */
  :deep(.el-tree-select) {
    width: 200px !important;
    min-width: 200px;
  }

  :deep(.el-tree-select .el-input__wrapper) {
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    transition: all 0.3s ease;
    height: 32px;
    min-height: 32px;
    display: flex;
    align-items: center;
  }

  :deep(.el-tree-select .el-input__wrapper:hover) {
    border-color: #c0c4cc;
  }

  :deep(.el-tree-select .el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  :deep(.el-tree-select .el-input__inner) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    padding: 0 12px;
    height: 32px;
    width: 100%;
    min-width: 0;
  }

  :deep(.el-tree-select .el-input__inner::placeholder) {
    color: #c0c4cc;
    font-size: 14px;
  }

  /* 单位选择器 */
  :deep(.el-select) {
    width: 200px !important;
    min-width: 200px;
  }

  :deep(.el-select .el-input__wrapper) {
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    transition: all 0.3s ease;
    height: 32px;
    min-height: 32px;
    display: flex;
    align-items: center;
  }

  :deep(.el-select .el-input__wrapper:hover) {
    border-color: #c0c4cc;
  }

  :deep(.el-select .el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  :deep(.el-select .el-input__inner) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    padding: 0 12px;
    height: 32px;
    width: 100%;
    min-width: 0;
  }

  :deep(.el-select .el-input__inner::placeholder) {
    color: #c0c4cc;
    font-size: 14px;
  }

  /* 仓库名称选择器 */
  :deep(.el-select:has(.el-form-item__label:contains("仓库名称"))) {
    width: 200px !important;
    min-width: 200px;
  }

  /* 下拉选项样式 */
  :deep(.el-select-dropdown) {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border: 1px solid #e4e7ed;
    z-index: 3000;
  }

  :deep(.el-select-dropdown .el-select-dropdown__item) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    padding: 12px 16px;
    transition: all 0.2s ease;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  :deep(.el-select-dropdown .el-select-dropdown__item:hover) {
    background-color: #f5f7fa;
    color: #409eff;
  }

  :deep(.el-select-dropdown .el-select-dropdown__item.selected) {
    background-color: #409eff;
    color: #ffffff;
    font-weight: 500;
  }

  /* 树形选择器下拉菜单 */
  :deep(.el-tree-select-dropdown) {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border: 1px solid #e4e7ed;
    z-index: 3000;
  }

  :deep(.el-tree-select-dropdown .el-tree-node__content) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    padding: 8px 16px;
    transition: all 0.2s ease;
  }

  :deep(.el-tree-select-dropdown .el-tree-node__content:hover) {
    background-color: #f5f7fa;
  }

  /* 确保输入框有正确的宽度 */
  :deep(.el-input) {
    width: 200px !important;
    min-width: 200px;
  }

  :deep(.el-input .el-input__wrapper) {
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    transition: all 0.3s ease;
    height: 32px;
    min-height: 32px;
    display: flex;
    align-items: center;
  }

  :deep(.el-input .el-input__wrapper:hover) {
    border-color: #c0c4cc;
  }

  :deep(.el-input .el-input__wrapper.is-focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  :deep(.el-input .el-input__inner) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    padding: 0 12px;
    height: 32px;
    width: 100%;
    min-width: 0;
  }

  :deep(.el-input .el-input__inner::placeholder) {
    color: #c0c4cc;
    font-size: 14px;
  }

  /* 复选框样式 */
  :deep(.el-checkbox__label) {
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    white-space: nowrap;
  }

  /* 按钮样式 */
  :deep(.el-button) {
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    transition: all 0.3s ease;
    height: 32px;
    padding: 0 20px;
    min-width: 80px;
  }

  :deep(.el-button--primary) {
    background-color: #409eff;
    border-color: #409eff;
  }

  :deep(.el-button--primary:hover) {
    background-color: #66b1ff;
    border-color: #66b1ff;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }

  :deep(.el-button:not(.el-button--primary):hover) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    :deep(.el-form-item) {
      margin-right: 0;
      margin-bottom: 15px;
    }

    :deep(.el-select),
    :deep(.el-tree-select),
    :deep(.el-input) {
      width: 100% !important;
      min-width: 100% !important;
    }

    .search-filter-section {
      padding: 15px;
    }
  }
}
</style>
